import React from 'react';
import { connect } from 'dva';
import { Link, browserHistory } from 'dva/router';
import { Table, Row, Col, Form, Input, Radio, Select, Button, message, Popconfirm, Badge } from 'antd';
import MessageDetail from '../../../../src/components/messageCenter/MessageDetail'
import RightBox from "../../../components/commons/RightBox";
import RIGHT from "../../../utils/RightConstants";
import Constants from "../../../utils/Constants";
const R = require('ramda');


const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
export default connect(({ messageCenter }) => ({ messageCenter }))(
    Form.create()(class MessageCenter extends React.Component {
        constructor(props) {
            super(props);
             this.state = {
                tempSelectMsgKeys: [],
                tempSelectMsg: []
            } 
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'messageCenter/queryMessages',
                payload: {
                    isReady: null
                }
            });
            this.props.dispatch({type: 'messageCenter/getUnReadCount'});
        }

        handleViewMessage = (record) => {
            this.props.dispatch({
                type: 'messageCenter/getMsgById',
                payload: {
                    id: record.id,
                    onSuccess: () => {
                        this.props.dispatch({
                            type: 'messageCenter/updateMsgReady',
                            payload: {
                                id: record.id,
                                onSuccess: record.isready === "0" ? () => {
                                    this.props.dispatch({
                                        type: 'messageCenter/setUnReadCount',
                                        payload: {
                                            unReadCount: this.props.messageCenter.unReadCount - 1
                                        }
                                    });
                                } : null
                            }
                        });
                    }
                }
            });
            this.refs.MessageDetail.handleOpen();
        }

        handleSearch = (event, flag, again) => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.messageCenter.page;
            newPage.page = flag ? newPage.page : 1;
            this.props.dispatch({
                type: 'messageCenter/queryMessages',
                payload: {
                    ...values,
                    page: newPage,
                    onSuccess: again ? (list) => {
                        if(R.isEmpty(list) && newPage.page > 1){
                            newPage.page = newPage.page - 1;
                            this.props.dispatch({
                                type: 'messageCenter/queryMessages',
                                payload: {
                                    ...values,
                                    page: newPage
                                }
                            })
                        }
                    } : null
                }
            });
        };

        handleDelete = (record) => {
            this.props.dispatch({
                type: 'messageCenter/deleteMsgById',
                payload: {
                    id: record.id,
                    onSuccess: () => {
                        this.props.dispatch({type: 'messageCenter/getUnReadCount'});
                        this.handleSearch(null, true, true);
                    }
                }
            });
        };

        handleBatchDelete = () => {
            if(R.isNil(this.state.tempSelectMsgKeys) || R.isEmpty(this.state.tempSelectMsgKeys)){
                message.info("亲，先选一个！");
                return;
            }
            this.props.dispatch({
                type: 'messageCenter/deleteMsgs',
                payload: {
                    ids: this.state.tempSelectMsgKeys,
                    onSuccess: () => {
                        this.setState({tempSelectMsgKeys: [], tempSelectMsg: []});
                        this.props.dispatch({type: 'messageCenter/getUnReadCount'});
                        this.handleSearch(null, true, true);
                    }
                }
            });
        };

        columns = [
            {
                title: '发送人', dataIndex: 'sender', key: 'sender',
                render: (text, record, index) => {
                    return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{"SYSTEM"}</span>
                }
            },
            {
                title: '发送日期', dataIndex: 'rectime', key: 'rectime',
                render: (text, record, index) => {
                    return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{record.rectime}</span>
                }
            },
            {
                title: '所属模块', dataIndex: 'type', key: 'type',
                render: (text, record, index) => {
                    return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{Constants.MESSAGEMODULE[record.type]}</span>
                }
            },
            {
                title: '标题', dataIndex: 'title', key: 'title',
                render: (text, record, index) => {
                    return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{record.title}</span>
                }
            },
            {
                title: '操作', key: 'key_oprator',
                render: (text, record, index) => {
                    return (
                        <div>
                            <a href="#" onClick={this.handleViewMessage.bind(this, record)}>查看</a>
                            <span className="ant-divider" />
                            <a href="#" onClick={this.handleDelete.bind(this, record)}>删除</a>
                        </div>
                    )
                }
            }];

        render() {
            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 4 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.messageCenter.page.size,
                total: this.props.messageCenter.page.totalRow,
                showSizeChanger: true,
                current: this.props.messageCenter.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.messageCenter.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'messageCenter/queryMessages',
                        payload: {
                            isReady: values.isReady,
                            page: newPage,
                            type: values.type,
                            title: values.title
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    this.setState({
                        tempSelectMsgKeys: [],
                        tempSelectMsg: []
                    })
                    let newPage = this.props.messageCenter.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'messageCenter/queryMessages',
                        payload: {
                            isReady: values.isReady,
                            page: newPage,
                            type: values.type,
                            title: values.title
                        }
                    });
                }
            }

             let rowSelection = {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({
                        tempSelectMsgKeys: selectedRowKeys,
                        tempSelectMsg: selectedRows
                    })
                },
                selectedRowKeys: this.state.tempSelectMsgKeys
            }; 

            return (
                <div>
                    <Row>
                        <Col span={3}><FormItem {...{ labelCol: { span: 7 }, wrapperCol: { span: 3 } }} label={'新消息'}>
                            <div style={{color: 'red'}}>{this.props.messageCenter.unReadCount > 99 ? '99+' :  this.props.messageCenter.unReadCount}</div>
                        </FormItem></Col>
                        <Col span={4}><FormItem {...{ labelCol: { span: 6 }, wrapperCol: { span: 8 } }} label={'类型'}>{getFieldDecorator('isReady')(
                            <Select style={{ width: '100%' }}>
                                <Option value={""} key="all">全部</Option>
                                <Option value="1" key="1">已读</Option>
                                <Option value="0" key="0">未读</Option>
                            </Select>
                        )}</FormItem></Col>
                        <Col span={4}><FormItem {...{ labelCol: { span: 6 }, wrapperCol: { span: 8 } }} label={'所属模块'}>{getFieldDecorator('type')(
                            <Select style={{ width: '100%' }}>
                                <Option value={""} key="all">全部</Option>
                                <Option value="customer" key="customer">客户</Option>
                                <Option value="product" key="product">产品</Option>
                                <Option value="drawer" key="drawer">开票人</Option>
                                <Option value="order" key="order">订单</Option>
                                <Option value="statement" key="statement">付款</Option>
                                <Option value="agreement" key="agreement">业务合同</Option>
                            </Select>
                        )}</FormItem></Col>
                        <Col span={4}><FormItem {...{ labelCol: { span: 6 }, wrapperCol: { span: 12 } }} label={'标题'}>{getFieldDecorator('title')(
                            <Input/>
                        )}</FormItem></Col>
                        <Col span={1}>
                            <Button type="primary" icon="search" onClick={this.handleSearch.bind(this)}>查询</Button>
                        </Col>
                        <Col span={1}>
                            <Button style={{marginLeft: 30}} type="primary" icon="delete" onClick={this.handleBatchDelete.bind(this)}>批量删除</Button>
                        </Col>
                    </Row>
                    <Table rowKey={record => record.id} dataSource={this.props.messageCenter.list} columns={this.columns} bordered={true} size={'middle'} rowSelection={rowSelection} pagination={pagination} />
                    <MessageDetail ref="MessageDetail" dataSource={this.props.messageCenter.messageDetail} refreshList={this.handleSearch}/>
                </div>
            )
        }
    })
)
